package forum.service.rpc;

import com.alibaba.druid.util.StringUtils;
import com.foreveross.springboot.dubbo.utils.BeanHelper;
import forum.domain.Token;
import forum.domain.User;
import forum.repository.RoleRepository;
import forum.repository.UserRepository;
import forum.repository.UserRoleRepository;
import forum.service.rpc.api.TokenService;
import forum.service.rpc.api.UserService;
import forum.service.tools.BaseSearch;
import forum.service.tools.SearchDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017/4/5.
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Override
    public Object getUserList(@QueryParam("page") @DefaultValue("0") int page,
                                @QueryParam("size") @DefaultValue("50") int size,
                                @QueryParam("sort") @DefaultValue("sort=userid,desc") String sort,
                                @QueryParam("operation") @DefaultValue("operation=eq") String operation,
                                @QueryParam("key") @DefaultValue("key=userid") String key,
                                @QueryParam("value") @DefaultValue("1") String value) {
//        logger.debug("get roles: {} . -> {}", "GET /api/v1/roles/", sort);

            // 简单适配, 暂无严谨性
            sort = sort.replaceAll("sort=", "").trim(); // sort=firstname,desc
            String[] sort_arr = sort.split(",");
            Sort.Direction direction;
            if (sort_arr[1] != null && "desc".equals(sort_arr[1])) {
                direction = Sort.Direction.DESC;
            } else {
                direction = Sort.Direction.ASC;
            }
            String[] properties = sort_arr[0].split("&");

            Sort _sort = new Sort(direction, Arrays.asList(properties));
            Pageable pageable = new PageRequest(page, size, _sort);
//        List<User> userlist = new ArrayList();
//        Page<User> _userlist = new Page<User>(userRepository.findAll(pageable));
            if (StringUtils.isEmpty(key) || StringUtils.isEmpty(operation) || StringUtils.isEmpty(value)) {
                logger.info("提示: key或者operation或者value为空 ");
//            userlist = userRepository.findAll(pageable).getContent();
//            _userlist =  userRepository.findAll(pageable);
            }

            if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(operation) && !StringUtils.isEmpty(value)) {
                logger.info("提示: key并且operation并且value都不为空 ");
//            userlist = userRepository.findAll(new BaseSearch<User>(new SearchDto(key,operation, value)),pageable).getContent();
                return userRepository.findAll(new BaseSearch<User>(new SearchDto(key, operation, value)), pageable);
            }
//        List<Role> list = roleRepository.getRolesByUserId(id);
//          for(Integer i = 0; i < size; i++){
//              if ((page * size + i) >= userlist.size()) {//3*2+2<7?
//                  logger.info("page * size + i = " + (page * size + i));
//              } else {
//                  userlist.get(page * size + i).setRoles(roleRepository.getRolesByUserId(userlist.get(page * size + i).getUserid()));
//              }
//          }

            return userRepository.findAll(pageable);
//        return userlist;

    }


    @Override
    public Object getUserById(Integer id) {
        User user = userRepository.findOne(id);
//        if (user != null) {
//            List<Role> list = roleRepository.getRolesByUserId(id);
//            user.setRoles(list);
//            return user;
//        } else {
//            return null;
//        }
        return user;
    }

    @Override
    public Object createUser(User user) {
        if (user != null) {
            List<User> list =  userRepository.findByUsername(user.getUsername());
            if (list != null && list.size() != 0) {
                return user.getUsername() + " 用户名已经被使用！";
            }
                userRepository.save(user);
        }
        return user;
    }

    @Override
    public Object updateUserById( @RequestBody User jsonObj) {
        User user = null;
        if (jsonObj != null) {
            List<User> list =  userRepository.findByUsername(jsonObj.getUsername());
            if (list != null && list.size() != 0) {
                return jsonObj.getUsername() + " 用户名已经被使用！";
            }
            if (jsonObj.getUserid() != null && jsonObj.getUserid() > 0) {
                user = userRepository.findOne(jsonObj.getUserid());
                if(user!=null){
                    BeanHelper.mapPartOverrider(user, jsonObj);
                    userRepository.save(user);
                }else {
                    return "没找到该ID的对象";
                }

            }else {
                return "id为空";
            }
        }


        return user;
    }

    @Override
    @Transactional
    public Object deleteUserByIds(Integer[] ids) {
        boolean flag = false;
        if (ids != null && ids.length > 0) {
            for (int i=0;i<ids.length;i++){
               User user = userRepository.findOne(ids[i]);
                if (user!=null){
                    userRepository.delete(ids[i]);
                    userRoleRepository.deleteByUserid(ids[i]);
                }else{
                    logger.info("id不存在");
                }

            }

//            userRoleRepository.deleteUserRolesByUserIds(ids);
            flag = true;
        }
        return flag;
    }


}
